#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QRegularExpression>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_model = new QStandardItemModel(2, FixedColumnCount, this);
    m_selection = new QItemSelectionModel(m_model, this);
    connect(m_selection, &QItemSelectionModel::currentChanged, this, &MainWindow::do_currentChanged);

    ui->tableView->setModel(m_model);
    ui->tableView->setSelectionModel(m_selection);
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectItems);
    this->setCentralWidget(ui->splitter);

    labCurFile = new QLabel("当前文件", this);
    labCurFile->setMinimumWidth(200);
    labelCellPos = new QLabel("当前单元格", this);
    labelCellPos->setMinimumWidth(180);
    labelCellPos->setAlignment(Qt::AlignHCenter);
    labCellText = new QLabel("单元格内容", this);
    labCellText->setMinimumWidth(150);
    labCellText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    ui->statusbar->addWidget(labCurFile);
    ui->statusbar->addWidget(labelCellPos);
    QWidget *spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    spacer->setMinimumWidth(300);
    ui->statusbar->addWidget(spacer);
    ui->statusbar->addWidget(labCellText);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::do_currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous);
    if(current.isValid())
    {
        //ui->actInsert->setEnabled(true);
        labelCellPos->setText(QString::asprintf("当前单元格：%d行，%d列", current.row(), current.column()));
        // labelCellPos->setText("当前单元格内容：" + current.data().toString());
        QStandardItem* item = m_model->itemFromIndex(current);
        labCellText->setText("单元格内容: " +  item->text());
        QFont font = item->font();
        ui->actFontBold->setChecked(font.bold());
    }
}

void MainWindow::on_actOpen_triggered()
{
    QString path = QCoreApplication::applicationDirPath();
    QString fileName = QFileDialog::getOpenFileName(this, "打开文件", path, "文本文件(*.txt);; 所有文件(*.*)");
    if(fileName.isEmpty())
        return;
    QStringList aFileContent;
    QFile aFile(fileName);
    if(aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream aStream(&aFile);
        ui->plainTextEdit->clear();
        while(!aStream.atEnd())
        {
            QString str = aStream.readLine();
            ui->plainTextEdit->appendPlainText(str);
            aFileContent.append(str);
        }
        aFile.close();
        labCurFile->setText("当前文件：" + fileName);
        ui->actAppend->setEnabled(true);
        ui->actInsert->setEnabled(true);
        ui->actDelete->setEnabled(true);
        ui->actSave->setEnabled(true);
        InitModelData(aFileContent);
    }
}

void MainWindow::InitModelData(QStringList &aFileContent)
{
    int rowCount = aFileContent.size();
    m_model->setRowCount(rowCount - 1);
    QString header = aFileContent.at(0);
    QStringList headerList = header.split(QRegularExpression("\\s+"),  Qt::SkipEmptyParts);
    m_model->setHorizontalHeaderLabels(headerList);

    int j;
    QStandardItem *aItem;
    for(int i = 1; i < rowCount; ++i)
    {
        QString aLineText = aFileContent.at(i);
        QStringList tmpList = aLineText.split(QRegularExpression("\\s+"),  Qt::SkipEmptyParts);
        for(j = 0; j < FixedColumnCount - 1; ++j)
        {
            aItem = new QStandardItem(tmpList.at(j));
            m_model->setItem(i-1, j, aItem);
        }

        aItem = new QStandardItem(headerList.at(j));
        aItem->setCheckable(true);
        aItem->setBackground(QBrush(Qt::yellow));
        if(tmpList.at(j) == "0")
            aItem->setCheckState(Qt::Unchecked);
        else
            aItem->setCheckState(Qt ::Checked);
        m_model->setItem(i - 1, j, aItem);
    }
}

void MainWindow::on_actAppend_triggered()
{
    QList<QStandardItem*> aItemList;
    QStandardItem *aItem;
    for(int i = 0; i < FixedColumnCount - 1; ++ i)
    {
        aItem = new QStandardItem("0");
        aItemList << aItem;
    }
    QString str = m_model->headerData(m_model->columnCount() - 1, Qt::Horizontal, Qt::DisplayPropertyRole).toString();
    aItem = new QStandardItem(str);
    aItem->setCheckable(true);
    aItemList << aItem;

    m_model->insertRow(m_model->rowCount(), aItemList);
    QModelIndex curIndex = m_model->index(m_model->rowCount() - 1, 0);
    m_selection->clearSelection();
    m_selection->setCurrentIndex(curIndex, QItemSelectionModel::SelectionFlag::Select);
}

void MainWindow::on_actInsert_triggered()
{
    QList<QStandardItem*> aItemList;
    QStandardItem *aItem;
    for(int i = 0; i < FixedColumnCount - 1; ++ i)
    {
        aItem = new QStandardItem("0");
        aItemList << aItem;
    }

    QModelIndex curIndex = m_selection->currentIndex();
    QString str = m_model->headerData(m_model->columnCount() - 1, Qt::Horizontal, Qt::DisplayPropertyRole).toString();
    aItem = new QStandardItem(str);
    aItem->setCheckable(true);
    aItemList << aItem;

    m_model->insertRow(curIndex.row(), aItemList);
    //m_selection->setCurrentIndex(curIndex, QItemSelectionModel::SelectionFlag::Select);
}

void MainWindow::on_actDelete_triggered()
{
    QModelIndex curIndex =  m_selection->currentIndex();
    if(curIndex.row() == m_model->rowCount() - 1)
        m_model->removeRow(curIndex.row());
    else
    {
        m_model->removeRow(curIndex.row());
        m_selection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
    }
}

void MainWindow::on_actAlignLeft_triggered()
{
    if(!m_selection->hasSelection())
        return;
    QModelIndexList indexList = m_selection->selectedIndexes();
    for(const auto &e : indexList)
    {
        m_model->itemFromIndex(e)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    }
}

void MainWindow::on_actAlignCenter_triggered()
{
    if(!m_selection->hasSelection())
        return;
    QModelIndexList indexList = m_selection->selectedIndexes();
    for(const auto &e : indexList)
    {
        m_model->itemFromIndex(e)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    }
}

void MainWindow::on_actAlignRight_triggered()
{
    if(!m_selection->hasSelection())
        return;
    QModelIndexList indexList = m_selection->selectedIndexes();
    for(const auto &e : indexList)
    {
        m_model->itemFromIndex(e)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
    }
}

void MainWindow::on_actFontBold_triggered(bool checked)
{
    if(!m_selection->hasSelection())
        return;
    QModelIndexList indexList = m_selection->selectedIndexes();
    for(const auto &e : indexList)
    {
        QFont font = m_model->itemFromIndex(e)->font();
        font.setBold(checked);
        m_model->itemFromIndex(e)->setFont(font);
    }
}

void MainWindow::on_actModelData_triggered()
{
    ui->plainTextEdit->clear();
    QStringList strList;
    QString str;
    for(int i = 0; i < m_model->columnCount(); ++ i)
    {
        strList << m_model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
    }
    // for(const auto &e : strList)
    // {
    //     if(e != strList.at(strList.size() - 1))
    //         str = str + e + "\t";
    //     else
    //         str = str + e;
    // }
    for(int i = 0; i < strList.size() - 1; ++ i)
        str = str + strList.at(i) + "\t";
    str += strList.last();

    ui->plainTextEdit->appendPlainText(str);

    for(int i = 0; i < m_model->rowCount(); ++ i)
    {
        str.clear();
        for(int j = 0; j < m_model->columnCount() - 1; ++ j)
        {
            str = str + m_model->item(i, j)->text() + "\t";
        }

        QStandardItem* item = m_model->item(i, m_model->columnCount() - 1);
        if(item->checkState() == Qt::Checked)
            str += QString::number(1);
        else
            str += QString::number(0);

        ui->plainTextEdit->appendPlainText(str);
    }
}

void MainWindow::on_actSave_triggered()
{
    QString path = QCoreApplication::applicationDirPath();
    QString fileName = QFileDialog::getSaveFileName(this, "保存文件", path, "文本文件(*.txt;; 所有文件(*.*)");
    if(fileName.isEmpty())
        return;
    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QStringList strList;
        QString str;
        QTextStream out(&file);
        for(int i = 0; i < m_model->columnCount(); ++ i)
        {
            strList << m_model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
        }
        // for(const auto &e : strList)
        // {
        //     if(e != strList.at(strList.size() - 1))
        //         str = str + e + "\t";
        //     else
        //         str = str + e;
        // }
        for(int i = 0; i < strList.size() - 1; ++ i)
            str = str + strList.at(i) + "\t";
        str += strList.last();
        // file.write(str.toUtf8() + "\n");
        out << str << Qt::endl;

        for(int i = 0; i < m_model->rowCount(); ++ i)
        {
            str.clear();
            for(int j = 0; j < m_model->columnCount() - 1; ++ j)
            {
                str = str + m_model->item(i, j)->text() + "\t";
            }

            QStandardItem* item = m_model->item(i, m_model->columnCount() - 1);
            if(item->checkState() == Qt::Checked)
                str += QString::number(1);
            else
                str += QString::number(0);

            // file.write(str.toUtf8() + "\n");
            out << str << Qt::endl;
        }
        file.close();
    }
}

